//
//  RBAddresssListVC.m
//  zhongzhenglu
//
//  Created by XL on 2022/7/15.
//

#import "RBAddresssListVC.h"
#import <UIColor+YYAdd.h>
#import "RBThemeConfig.h"
#import <UIControl+YYAdd.h>
#import "UIView+RBAdd.h"
#import "RBDefine.h"
#import <Masonry.h>
#import "UIButton+RBAdd.h"
#import "RBProfileVC.h"
#import "UIScrollView+RBAdd.h"
#import "RBAddressListCell.h"
#import "RBAddressAddVC.h"
#import "RBAddressListResponse.h"
#import "UIViewController+RBAdd.h"
#import "RBRefreshHeader.h"
#import "RBRefreshFooter.h"

@interface RBAddresssListVC ()<UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray *dataSource;
@property(nonatomic, strong)UIButton *addBtn;

@property(nonatomic, strong) RBAddressListResponse *response;

@end

@implementation RBAddresssListVC

#pragma mark - Lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setup];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark - Private

- (void)setup
{
    self.title = @"收货地址";
    self.view.backgroundColor = [RBThemeConfig bgGrayColor];
}

- (void)fillData
{
    [self.dataSource removeAllObjects];
    [self.dataSource addObject:({
        RBGroupModel *group = RBGroupModel.new;
        group.cellModels = ({
            NSMutableArray *arrayM = NSMutableArray.array;
            arrayM;
        });
        group;
    })];
    [self appendData];
    
}

- (void)appendData
{
    __weak typeof(self) weak_self = self;
    NSMutableArray *arrayM = ({
        RBGroupModel *group = self.dataSource.firstObject;
        (NSMutableArray *)group.cellModels;
    });
    for (RBAddressListModel *model in self.response.data)
    {
        [arrayM addObject:({
            RBCellModel *cellModel = RBCellModel.new;
            cellModel.reuseCellIdentifier = NSStringFromClass(RBAddressListCell.class);
            cellModel.cellData = model;
            cellModel.eventBlock1 = ^(NSInteger type, NSInteger index, id data) {
                if(type == 0)
                {
                    [weak_self setDefaultEvent:data];
                }
                else if(type == 1)
                {
                    [weak_self editEvent:data];
                }
            };
            cellModel.cellSelectBlock = ^(NSIndexPath *indexPath) {
                RBAddressListModel *model = [RanTool modelWithSection:indexPath.section row:indexPath.row dataSource:weak_self.dataSource];
                if(weak_self.selectBlock)
                {
                    weak_self.selectBlock(model);
                    [weak_self.navigationController popViewControllerAnimated:YES];
                }
            };
            cellModel;
        })];
    }
    [self.tableView reloadData];
    if(!arrayM.count)
    {
        [self.tableView showPlaceHolder:RB_EMPTY_TIP tapBlock:nil];
    }
}

#pragma mark - Network

- (NSString *)listPageKey
{
    return @"page";
}
- (NSDictionary *)listParams
{
    return @{
        @"user_id":[RBAccountManager getUserId],
    };
}
- (NSString *)listRequestPath
{
    return @"hu_address";
}
- (NSInteger)ListCurrentPage
{
    return self.response.currentPage;
}
- (BOOL)listLog
{
    return YES;
}
- (BOOL)listPost
{
    return YES;
}
- (Class)listResponseClass
{
    return RBAddressListResponse.class;
}
- (UIScrollView *)listView
{
    return self.tableView;
}

- (void)getFirstPageData
{
    __weak typeof(self) weak_self = self;
    [self listLoadFirstPageWithDesView:self.tableView showPlaceHolder:YES sucBlock:^(id data) {
        weak_self.response = data;
        [weak_self fillData];
    } failBlock:^(id data) {
        
    } reloadBlock:^{
        [weak_self getFirstPageData];
    }];
}

- (void)getNextPageData
{
    __weak typeof(self) weak_self = self;
    [self listLoadNextPageWithSucBlock:^(id data) {
        weak_self.response = data;
        [weak_self appendData];
    } failBlock:^(id data) {
        
    }];
}

- (void)setDefaultRequestWithModel: (RBAddressListModel *)model
{
    __weak typeof(self) weak_self = self;
    [self viewLoadDataWithParam:^(NSMutableDictionary *dicM) {
        dicM[@"add_id"] = model.add_id;
    } path:@"hu_address_moren" post:YES log:YES responseClass:RBResponse.class desView:self.view showHud:YES showPlaceHolder:NO sucBlock:^(id data) {
        [weak_self.view showTip:@"操作成功" completion:nil];
        [weak_self.listView.mj_header beginRefreshing];
    } failBlock:^(RBResponse *data) {
        [weak_self.view showTip:data.message completion:nil];
    } reloadBlock:nil];
}

- (void)deleteRequestWithModel: (RBAddressListModel *)model
{
    __weak typeof(self) weak_self = self;
    [self viewLoadDataWithParam:^(NSMutableDictionary *dicM) {
        dicM[@"add_id"] = model.add_id;
    } path:@"hu_address_del" post:YES log:YES responseClass:RBResponse.class desView:self.view showHud:YES showPlaceHolder:NO sucBlock:^(id data) {
        [weak_self.view showTip:@"删除成功" completion:nil];
        [weak_self.listView.mj_header beginRefreshing];
    } failBlock:^(RBResponse *data) {
        [weak_self.view showTip:data.message completion:nil];
    } reloadBlock:nil];
}

#pragma mark - Event

- (void)addBtnTapped
{
    RBAddressAddVC *vc = RBAddressAddVC.new;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)setDefaultEvent: (RBAddressListModel *)model
{
    if(model.moren.intValue == 1)
    {
        [self.view showTip:@"该地址已是默认地址" completion:nil];
        return;
    }
    [self setDefaultRequestWithModel:model];
}

- (void)editEvent: (RBAddressListModel *)model
{
    __weak typeof(self) weak_self = self;
    UIAlertController *vc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [vc addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [vc addAction:[UIAlertAction actionWithTitle:@"修改" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        RBAddressAddVC *vc = RBAddressAddVC.new;
        vc.model = model;
        [weak_self.navigationController pushViewController:vc animated:YES];
    }]];
    [vc addAction:[UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [weak_self deleteRequestWithModel:model];
    }]];
    [self presentViewController:vc animated:YES completion:nil];

}

#pragma mark - UITableViewDataSource & Delegate

kRBTableViewDataSourceAndDelegate(self.dataSource);

#pragma mark - Setter

#pragma mark - Getter

- (UITableView *)tableView
{
    if (!_tableView)
    {
        self.tableView = ({
            UITableView *view = [UITableView.alloc initWithFrame:CGRectZero style:UITableViewStylePlain];
            view.dataSource = self;
            view.delegate = self;
            view.showsVerticalScrollIndicator = NO;
            view.showsHorizontalScrollIndicator = NO;
            kRBIgnoreScrollViewInsetsAdjust(view);
            view.separatorStyle = UITableViewCellSeparatorStyleNone;
            view.tableFooterView = UIView.new;
            view.backgroundColor = UIColor.clearColor;
            view.estimatedRowHeight = UITableViewAutomaticDimension;
            view.mj_header = [RBRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(getFirstPageData)];
            view.mj_footer = [RBRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(getNextPageData)];
            [self.view addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.mas_equalTo(0);
                make.top.mas_equalTo(0);
                make.bottom.mas_equalTo(self.addBtn.mas_top).offset(Zoom(-18));
            }];
            view;
        });
    }
    return _tableView;
}

- (NSMutableArray *)dataSource
{
    if (!_dataSource)
    {
        self.dataSource = ({
            NSMutableArray *arrayM = NSMutableArray.array;
            arrayM;
        });
    }
    return _dataSource;
}

- (UIButton *)addBtn
{
    if (!_addBtn)
    {
        self.addBtn = ({
            UIButton *view = UIButton.new;
            [view rbAddTarget:self action:@selector(addBtnTapped)];
            [view rbSetTitle:@"新增地址"];
            [view rbSetTitleColor:UIColor.whiteColor];
            [view rbSetFont:[UIFont systemFontOfSize:Zoom(15)]];
            [view rbSetCornerRadius:Zoom(22)];
            view.backgroundColor = [UIColor colorWithHexString:@"#518CFF"];
            [self.view addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.mas_equalTo(-MAX(Zoom(25), kRBSafeBottomHeight));
                make.centerX.mas_equalTo(0);
                make.size.mas_equalTo(CGSizeMake(Zoom(339), Zoom(44)));
            }];
            view;
        });
    }
    return _addBtn;
}

@end
